/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wwcontrolserver.listeners;

//import com.phidgets.*;
import wwcontrolserver.datarecorders.WWDatabaseConnection;
import com.phidgets.event.DetachListener;
import com.phidgets.event.DetachEvent;
import com.phidgets.Phidget;
import org.tmatesoft.sqljet.core.SqlJetException;
import com.phidgets.PhidgetException;
import java.util.ArrayList;
import java.util.HashMap;
import wwcontrolserver.controls.ControlKey;
import wwcontrolserver.controls.ControlManager;
import wwcontrolserver.datarecorders.AbstractDataRecorder;
import wwcontrolserver.datarecorders.WWControlServerLogger;
import wwcontrolserver.ifk.AbstractIFK;
/**
 *
 * @author Michael Ferry
 */
public class WWDetachListener implements DetachListener{
    private final WWControlServerLogger WWCSLog;
    private final ArrayList<AbstractDataRecorder> DataRecList;
    private final HashMap IFKMap;
    private final ControlManager CManager;
    
    public WWDetachListener(WWControlServerLogger WWCSLog, ArrayList<AbstractDataRecorder> DataRecList, HashMap IFKMap, ControlManager CManager) {       
        this.WWCSLog = WWCSLog;
        this.DataRecList = DataRecList;
        this.IFKMap = IFKMap;
        this.CManager = CManager;
    }
    
    
    
    @Override
    public void detached(DetachEvent ae) {
        //System.out.println("detachment of " + ae);
        WWCSLog.RecordWarning("detachment of " + ae);

        try {

            Phidget PhidSource = ae.getSource();
            int SerialNumber = PhidSource.getSerialNumber();
            for (AbstractDataRecorder DataRec : DataRecList) {
                DataRec.InsertAttachDetachRecord(SerialNumber, false);
            }
            
            AbstractIFK AttachedIFK = (AbstractIFK) IFKMap.get(SerialNumber);
            AttachedIFK.ExecuteDefaultDetach();
            
            CManager.NotifyControlsUsingKey(new ControlKey(SerialNumber));
//        if (WWDB != null) {
//                try {
//                    WWDB.InsertAttachDetachRecord(SerialNumber, 0);
//                } catch (SqlJetException sqle) {
//                    System.out.println(sqle);
//                }
//            }
        } catch (PhidgetException phde) {
            WWCSLog.RecordExceptionLogEntry(phde);
        }
    }
}
